//
//  GuidTool.m
//  bluesharktv
//
//  Created by zhangcong on 16/2/2.
//  Copyright © 2016年 yaowang. All rights reserved.
//

#import "GuidTool.h"
#import "TYKeyChain.h"

static NSString * const KEY_IN_KEYCHAIN = @"device.allInfo";
static NSString * const KEY_PASSWORD = @"device.guid";
static NSString * const kGuidKey = @"device.guidkey";

static NSString * const KEY_IN_KEYCHAIN_SERVER = @"device.allInfo.server";
static NSString * const KEY_PASSWORD_SERVER = @"device.guid.server";
static NSString * const kGuidKey_SERVER = @"device.guidkey.server";


@implementation GuidTool

+ (void)saveGuid:(NSString *)guid {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    [setting setObject:guid forKey:kGuidKey];
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:guid forKey:KEY_PASSWORD];
    [TYKeyChain save:KEY_IN_KEYCHAIN data:usernamepasswordKVPairs];
}

+ (id)Guid {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    NSString *guid = [setting objectForKey:kGuidKey];
    if (!guid || guid.length < 10) {
        NSMutableDictionary *usernamepasswordKVPair = (NSMutableDictionary *)[TYKeyChain load:KEY_IN_KEYCHAIN];
        guid = [usernamepasswordKVPair objectForKey:KEY_PASSWORD];
        if ([guid length] < 10) {
            guid = [GuidTool makeGuid];
        }
        [GuidTool saveGuid:guid];
    }
    return guid;
}

+ (void)deleteGuid {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    [setting removeObjectForKey:kGuidKey];
    [TYKeyChain delete:KEY_IN_KEYCHAIN];
}

+(void)saveServerGuid:(NSString *)serverid {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    [setting setObject:serverid forKey:kGuidKey_SERVER];
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:serverid forKey:KEY_PASSWORD_SERVER];
    [TYKeyChain save:KEY_IN_KEYCHAIN_SERVER data:usernamepasswordKVPairs];
}
+(id)serverId {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    NSString *guid = [setting objectForKey:kGuidKey_SERVER];
    if (!guid || guid.length < 10) {
        NSMutableDictionary *usernamepasswordKVPair = (NSMutableDictionary *)[TYKeyChain load:KEY_IN_KEYCHAIN_SERVER];
        guid = [usernamepasswordKVPair objectForKey:KEY_PASSWORD_SERVER];
        if ([guid length] < 10) {
            guid = nil;
        }
    }
    return guid;

}
+(void)deleteServerId {
    NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
    [setting removeObjectForKey:kGuidKey_SERVER];
    [TYKeyChain delete:KEY_IN_KEYCHAIN_SERVER];
}

#pragma mark [获取 一个GUID]
+ (NSString *)makeGuid
{
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    NSString  * uuidString = (__bridge NSString*)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    return uuidString;
}

@end
